﻿using Bricks.Business.Models.Account;
using Bricks.Component.Utils;
using Bricks.Business.Data.Repositories.Account;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;

namespace Bricks.Business.Service.Impl
{
    [Export(typeof(IOrgInfoService))]
    public class OrgInfoService : IOrgInfoService
    {
        [Import]
        protected IOrgInfoRepository OrgRepository { get; set; }
        [Import]
        protected IUserOrgRepository UserOrgRepository { get; set; }
        [Import]
        protected IUserInfoRepository UserRepository { get; set; }
        [Import]
        protected IMenuInfoRepository MenuInfoRepository { get; set; }
        [Import]
        protected IOrgMenuActionRepository OrgMenuActionRepository { get; set; }

        public IQueryable<OrgInfo> Orgs
        {
            get { return OrgRepository.Entities; }
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public OperationResult Add(OrgInfo model)
        {
            PublicHelper.CheckArgument(model, "model");
            OrgInfo record = model.CopyTo<OrgInfo>();
            record.ID = GuidHelper.NewGuid();
            record.OrderNo = OrgRepository.GetNextOrderNo(m => m.OrderNo);  //获取下一个排序号
            OrgRepository.Insert(record);

            return new OperationResult(OperationResultType.Success, "新增成功", record);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public OperationResult Modify(OrgInfo model)
        {
            PublicHelper.CheckArgument(model, "model");
            OrgInfo record = Orgs.FirstOrDefault(m => m.ID == model.ID);
            if (record == null)
                return new OperationResult(OperationResultType.QueryNull, "未找到指定的记录");

            record = model.CopyTo<OrgInfo>();
            if (OrgRepository.Update(record) >= 0)
            {
                //禁用机构的时候，同时禁用机构下的用户
                if (model.IsDeleted)
                {
                    var userOrgs = UserOrgRepository.Entities.Where(m => m.OrgID == model.ID);
                    foreach (var uo in userOrgs)
                    {
                        uo.IsDeleted = true;
                    }
                    UserOrgRepository.Update(userOrgs);
                }
                return new OperationResult(OperationResultType.Success, "修改成功", record);
            }
            return new OperationResult(OperationResultType.Error, "保存失败");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public OperationResult Delete(Guid id)
        {
            OrgInfo record = Orgs.FirstOrDefault(m => m.ID == id);
            if (record == null)
                return new OperationResult(OperationResultType.QueryNull, "未找到指定的记录");

            //查找该机构下是否包含用户，若包含用户，则不允许删除
            var isExistUserOrg = UserOrgRepository.Entities.Where(m => m.OrgID == id).Count() > 0;
            if (isExistUserOrg)
            {
                return new OperationResult(OperationResultType.Warning, "该机构下存在用户，不可删除");
            }

            //删除该机构对应的机构权限（机构菜单功能）
            var orgMenuActions = OrgMenuActionRepository.Entities.Where(m => m.OrgID == id);
            if (orgMenuActions != null && orgMenuActions.Count() > 0)
            {
                OrgMenuActionRepository.Delete(orgMenuActions);
            }

            if (OrgRepository.Delete(record) >= 0)
                return new OperationResult(OperationResultType.Success, "删除成功", record);
            return new OperationResult(OperationResultType.Error, "删除失败");
        }

        /// <summary>
        /// 排序设置(向上向下)
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <param name="upOrDown"></param>
        /// <returns></returns>
        public OperationResult SetOrder(Guid id, Guid? pid, string upOrDown)
        {
            IQueryable<OrgInfo> entities = null;
            if (pid.HasValue)
            {
                entities = OrgRepository.Entities.Where(m => m.PID == pid.Value);  //找出可能涉及排序的实体集合（同一PID下）
            }
            else
            {
                entities = OrgRepository.Entities.Where(m => m.PID == null);  //找出可能涉及排序的实体集合（同一PID下）
            }
            var exeResult = OrgRepository.SetOrder(entities, id, "OrderNo", upOrDown);  //执行向上向下操作
            return exeResult;
        }

        /// <summary>
        /// 获取用户菜单ID
        /// </summary>
        /// <returns></returns>
        public string GetAccountPageID()
        {
            string result = string.Empty;
            var menu = MenuInfoRepository.Entities.FirstOrDefault(m => m.MenuCode == "Account");
            if (menu != null)
            {
                result = menu.ID.ToString().ToLower();
            }
            return result;
        }


        public string GetOrgCodeByUserName(string userName)
        {
            var record = from orgInfo in OrgRepository.Entities
                         join orgUser in UserOrgRepository.Entities on orgInfo.ID equals orgUser.OrgID
                         join userInfo in UserRepository.Entities on orgUser.UserID equals userInfo.ID
                         where userInfo.UserName == userName
                         select orgInfo;
            return record.FirstOrDefault().OrgCode;
        }

        /// <summary>
        /// 根据ID获取机构名称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetOrgNameByID(Guid id)
        {
            string result = string.Empty;
            var org = OrgRepository.Entities.FirstOrDefault(m => m.ID == id);
            if (org != null)
            {
                result = org.OrgName;
            }
            return result;
        }

        /// <summary>
        /// 是否已经存在的机构编码
        /// </summary>
        /// <param name="org"></param>
        /// <param name="isModify"></param>
        /// <returns></returns>
        public bool IsExistOrgCode(OrgInfo org, bool isModify = true)
        {
            bool result = false;
            //新增：直接去数据库查有没有重复的
            if (!isModify)
            {
                result = Orgs.Count(m => m.OrgCode == org.OrgCode) > 0;
            }
            //修改：去数据库查除自己以为是否重复
            else
            {
                result = Orgs.Count(m => m.OrgCode == org.OrgCode && m.ID != org.ID) > 0;
            }
            return result;
        }
    }
}
